<?php

function checkFbAuth() {
    if (empty($_SESSION['fb_id']) || $_SESSION['fb_id'] == "") {
        echo "<script> window.location = 'index.php'</script>";
    }
}

function errRedirect($errorType, $errorMsg, $pageName, $errLine) {

    $errorMsg = urlencode($errorMsg);
    $pageName = urlencode($pageName);
    echo "<script>window.location='error_page.php?pagename=$pageName&errmsg=$errorMsg&errtype=$errorType&errline=$errLine'</script>";
}

function cleanURL($str, $replace=array(), $delimiter='-') {
    if (!empty($replace)) {
        $str = str_replace((array) $replace, ' ', $str);
    }

    $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
    $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
    $clean = strtolower(trim($clean, '-'));
    $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

    return $clean;
}

function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

function update_smsresult($body, $msisdn, $result, $orderid, $fb_id) {

    mysql_query("insert into tbl_sms_record(content,msisdn,order_id,return_result,fb_id,send_datetime)values
		('$body','$msisdn','$orderid','$result','$fb_id',now())") or die("line 15" . mysql_error());
}

function insertPointRecord($fb_id, $point_source, $total_points) {
    mysql_query("insert into tbl_points_record (fb_id,point_source,total_point,created_datetime)values('$fb_id','$point_source','$total_points',now())") or die(mysql_error());
}

function generatePassword($length=9, $strength=4) {
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength & 1) {
        $consonants .= 'BDGHJLMNPQRSTVWXZ';
    }
    if ($strength & 2) {
        $vowels .= "AEUY";
    }
    if ($strength & 4) {
        $consonants .= '23456789';
    }
    if ($strength & 8) {
        $consonants .= '#$%';
    }

    $password = '';
    $alt = time() % 2;
    for ($i = 0; $i < $length; $i++) {
        if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}

function convertAnswer($answer) {
    $return = "Unknown";
    switch ($answer) {
        case 1:
            $return = "A";
            break;
        case 2:
            $return = "B";
            break;
        case 3:
            $return = "C";
            break;

        case 4:
            $return = "D";
            break;
    }
    return $return;
}

function getDataById($table, $field, $byfield, $id) {
    $get = mysql_query("select $field from $table where $byfield='$id'") or die(mysql_error());
    if (mysql_num_rows($get) > 0) {
        $return = mysql_result($get, 0, $field);
    } else {
        $return = "unknown";
    }
    return $return;
}

function daysDifference($endDate, $beginDate) {
    //explode the date by "-" and storing to array
    $date_parts1 = explode("-", $beginDate);
    $date_parts2 = explode("-", $endDate);
    //gregoriantojd() Converts a Gregorian date to Julian Day Count
    $start_date = gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
    $end_date = gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
    return $end_date - $start_date;
}

function generate_check_key() {

    $salt = "1234567890";

    srand((double) microtime() * 1000000);
    $num = rand();
    $pass = time() . "_" . $num;

    return $pass;
}

function getPagingAjax($totalPerPage, $totalRecord, $currentPage, $pageUrl) {


    $totalpage = $totalRecord / $totalPerPage;

    if ($totalRecord % $totalPerPage > 0) {
        if (round($totalpage) > $totalpage) {
            $totalpage = round($totalpage);
        } else {
            $totalpage = round($totalpage + 1);
        }
    } else {
        $totalpage = round($totalpage);
    }


    $nextpage = $currentPage + 1;
    $prepage = $currentPage - 1;

    $output = "<table  cellpadding='0' cellspacing='0' >								
					<td height='45'>
						
						<a onclick='" . $pageUrl . "(" . $prepage . ")'><img src='images/icons/paging_pre.png' border=0 onmouseover='this.style.cursor=\"pointer\"'></a>
					</td>
					<td>
						<table>";

    if ($totalpage > 10) {

        $frompage = $currentPage - 2;


        if ($frompage <= 0 || $currentPage == 1 || $currentPage == 2) {
            $frompage = 1;
            $endpage = 10;
        } else {

            $endpage = $currentPage + 7;

            if ($endpage > $totalpage) {
                $endpage = $totalpage;
            }

            $testpage = 0;

            if ($currentPage > 2) {
                for ($paging = $frompage; $paging <= $endpage; $paging++) {

                    $testpage++;
                }

                if ($testpage < 10) {
                    $additionalpage = 10 - $testpage;

                    $frompage = $frompage - $additionalpage;
                }
            }
        }
    } else {
        $frompage = 1;
        $endpage = $totalpage;
    }

    for ($paging = $frompage; $paging <= $endpage; $paging++) {

        if ($paging == $currentPage) {
            $output.="<td align=center width='20px' class='paging_highlighted'>" . $paging . "</td>";
        } else {
            $output.="<td align=center width='20px' class='paging_outlighted'>
				<a onclick='" . $pageUrl . "(" . $paging . ")' style='text-decoration:none' onmouseover='this.style.cursor=\"pointer\"'>" . $paging . "</a></td>";
        }
    }

    $output.="</table></td><td>";

    if ($currentPage == $totalpage) {

        $output.="<img src='images/icons/paging_next.png' border=0>";
    } else {

        $output.=" <a onclick='" . $pageUrl . "(" . $nextpage . ")'><img src='images/icons/paging_next.png' border=0  onmouseover='this.style.cursor=\"pointer\"'></a>";
    }

    $output.=" </td></table>";

    return $output;
}

function getPaging($totalPerPage, $totalRecord, $currentPage, $pageUrl) {


    $totalpage = $totalRecord / $totalPerPage;

    if ($totalRecord % $totalPerPage > 0) {
        if (round($totalpage) > $totalpage) {
            $totalpage = round($totalpage);
        } else {
            $totalpage = round($totalpage + 1);
        }
    } else {
        $totalpage = round($totalpage);
    }


    $nextpage = $currentPage + 1;
    $prepage = $currentPage - 1;

    $output = "<table  cellpadding='0' cellspacing='0' >								
					<td height='45'>
						
						<a href='" . $pageUrl . "&page=" . $prepage . "'><img src='images/icons/paging_pre.png' border=0></a>
					</td>
					<td>
						<table>";

    if ($totalpage > 10) {

        $frompage = $currentPage - 2;


        if ($frompage <= 0 || $currentPage == 1 || $currentPage == 2) {
            $frompage = 1;
            $endpage = 10;
        } else {

            $endpage = $currentPage + 7;

            if ($endpage > $totalpage) {
                $endpage = $totalpage;
            }

            $testpage = 0;

            if ($currentPage > 2) {
                for ($paging = $frompage; $paging <= $endpage; $paging++) {

                    $testpage++;
                }

                if ($testpage < 10) {
                    $additionalpage = 10 - $testpage;

                    $frompage = $frompage - $additionalpage;
                }
            }
        }
    } else {
        $frompage = 1;
        $endpage = $totalpage;
    }

    for ($paging = $frompage; $paging <= $endpage; $paging++) {

        if ($paging == $currentPage) {
            $output.="<td align=center width='20px' class='paging_highlighted'>" . $paging . "</td>";
        } else {
            $output.="<td align=center width='20px' class='paging_outlighted'>
				<a href='" . $pageUrl . "&page=" . $paging . "' style='text-decoration:none'>" . $paging . "</a></td>";
        }
    }

    $output.="</table></td><td>";

    if ($currentPage == $totalpage) {

        $output.="<img src='images/icons/paging_next.png' border=0>";
    } else {

        $output.=" <a href='" . $pageUrl . "&page=" . $nextpage . "'><img src='images/icons/paging_next.png' border=0></a>";
    }

    $output.=" </td></table>";

    return $output;
}

function check_is_cp($url, $uid) {
    $check_key = generate_check_key();
    $chk_is_club_member = $url . "?fb_uid=$uid&check_key=$check_key";
    //echo $chk_is_club_member;
    $result = "0";

    $xml = simplexml_load_file($chk_is_club_member);
    $result = "";

    $no = 0;

    foreach ($xml->children() as $child) {
        if ($child->getName() == "result") {
            $result = $child;
        }

        if ($child->getName() == "error_msg") {
            $error_msg = $child;
        }
    }

    return $result;
}

function escapeJSString($string) {
    $js_escape = array("\r" => '\r',
        "\n" => '\n',
        "\t" => '\t',
        "'" => "\\'",
        '"' => "\\'",
        '\\' => '\\\\');

    return strtr($string, $js_escape);
}

function convertDate($date, $format) {

    $timestamp = strtotime($date);
    $returnDate = date($format, $timestamp);
    return $returnDate;
}

function getPhotoBox($a, $btn_vote, $btn_share) {

    $content = "
            <table id='Table_01' width='480' height='165' border='0' cellpadding='0' cellspacing='0' align='center'>
                <tr>
                    <td style='background-image:url(images/photo_box_01.jpg);background-repeat:no-repeat;background-position:top;background-color:#ffffff' width='194' height='165'>
                        <table cellpadding='10' width='100%'>
                        	<td align='center'>";

    if ($a['width'] > 120 or $a['height'] > 100) {
        if ($a['width'] - $a['height'] > 0) {
            $fix = 'width=130';
        } else {
            $fix = 'height=100';
        }
    } else {
        $fix = 'width=' . $a['width'];
    }
    $get_con = mysql_query('select * from tbl_contestant where id=' . $a['created_by']);
    $total_vote = mysql_result(mysql_query("select count(*) as result from tbl_votes where photo_id=" . $a['id']), 0, "result");

    $content.="<a href='album/" . $a['pic'] . "' target='_blank'><img src='album/" . $a['pic'] . "'  $fix  border='0' /></a>
                                <br />
                                <a href='album/" . $a['pic'] . "' target='_blank'><img src='images/btn_view.png' border='0' /></a>
                                
                            </td>
                        </table>
                    </td>
                    <td valign='top' style='background-image:url(images/photo_box_02.jpg);background-repeat:no-repeat;background-position:top;background-color:#ffffff' width='286' height='165'>
                    	<table cellpadding='10' align='center' width='100%'>
                     	<tr>
                        	<td width='80%'><font class='caption'>\"" . $a['caption'] . "\"</font></td>
                           	<td rowspan='2' valign='middle' align='center'>
                            	<a href='vote_this.php?id=" . $a['id'] . "'>";

    if ($btn_vote == 1) {
        $content.="<img src='images/btn_vote.png' border='0' /></a>
									
                               
                                <font style='font-size:10px'> " . $total_vote . " vote(s)</font>
                                <br />
								";
    }
    if ($btn_share == 1) {

        $content.="<a onclick=\"publishStream('http://www.dcinnovation.com/petronasbrands/album/" . $a['pic'] . "','" . escapeJSString($a['caption']) . "','" . $a['id'] . "'); return false;\">
								<img src='images/btn_share.png' border='0' /></a>";
    }
    $content.="		
                            </td>
                        </tr>
                        <tr>
                        	<td>
                            	<br />
                                <i><font style='font-size:10px'>By  " . mysql_result($get_con, 0, 'con_name') . "<br />
                                On  " . date('j F Y', strtotime($a['created_datetime'])) . "</font></i>
                            </td>
                        </tr>
                       
                     </table>
                    </td>
                </tr>
            </table><br><br>";

    echo $content;
}

function getPicStatus($status) {
    $return = "unknown status";
    switch ($status) {
        case 0:
            $return = "Waiting approval";
            break;
        case 1:
            $return = "Approved";
            break;
        case -1:
            $return = "Rejected";
            break;
    }
    return $return;
}

function getTimeDiff($time1, $time2, $precision = 6) {
    // If not numeric then convert texts to unix timestamps
    if (!is_int($time1)) {
        $time1 = strtotime($time1);
    }
    if (!is_int($time2)) {
        $time2 = strtotime($time2);
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
        $ttime = $time1;
        $time1 = $time2;
        $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array('year', 'month', 'day', 'hour', 'minute', 'second');
    $diffs = array();

    // Loop thru all intervals
    foreach ($intervals as $interval) {
        // Set default diff to 0
        $diffs[$interval] = 0;
        // Create temp time from time1 and interval
        $ttime = strtotime("+1 " . $interval, $time1);
        // Loop until temp time is smaller than time2
        while ($time2 >= $ttime) {
            $time1 = $ttime;
            $diffs[$interval]++;
            // Create new temp time from time1 and interval
            $ttime = strtotime("+1 " . $interval, $time1);
        }
    }

    $count = 0;
    $times = array();
    // Loop thru all diffs
    foreach ($diffs as $interval => $value) {
        // Break if we have needed precission
        if ($count >= $precision) {
            break;
        }
        // Add value and interval 
        // if value is bigger than 0
        if ($value > 0) {
            // Add s if value is not 1
            if ($value != 1) {
                $interval .= "s";
            }
            // Add value and interval to times array
            $times[] = $value . " " . $interval;
            $count++;
        }
    }

    // Return string with times
    return implode(", ", $times);
}

?>